package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //转换为子类 功能更丰富
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //放行的有静态页面 还有 controller 访问的数据
        //如果没有登录就访问其他页面就不可以放问拦截他
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login"
        };
        //进行逻辑判断 如果有里面的请求路径就进行放行
        String requestURI = req.getRequestURI();
        boolean check = check(urls, requestURI);
        if (check) {
            chain.doFilter(req, resp);
            return;
        }


        //获取session里面的登录id
        Long id = (Long) req.getSession().getAttribute("employee");
        //判断这个id是否为空如果不为空就放行
        if (id != null) {
            BaseContext.setId(id);
            chain.doFilter(req, resp);
            return;
        }

        //获取手机session里面的登录id
        Long userId = (Long) req.getSession().getAttribute("User");
        //判断这个id是否为空如果不为空就放行
        if (userId != null) {
            BaseContext.setId(userId);
            chain.doFilter(req, resp);
            return;
        }

        //如果没有登录就返回对应的数据到页面
        String notlogin = JSON.toJSONString(R.error("NOTLOGIN"));
        resp.getWriter().write(notlogin);
    }

    private boolean check(String[] urls, String requestURI) {
        //路径匹配器 支持通配符
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}

